package com.fw.cost.producer.service.researchCost.impl;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fw.cost.commons.config.TransactionManagerHelper;
import com.fw.cost.commons.excel.ImportUtils;
import com.fw.cost.commons.utils.FiscalYearUtils;
import com.fw.cost.commons.utils.UUIDUtils;
import com.fw.cost.model.entity.researchCost.ResearchProjCostSummaryModel;
import com.fw.cost.producer.service.researchCost.IResearchProjCostSummaryService;
import com.fw.cost.producer.mapper.ResearchProjCostSummaryMapper;

/**
* <b><code></code></b>
* <p/>
*
*  科研项目成本汇总表
*
* <p/>
* <b>Creation Time:</b> 2024/09/27 09:11:36
*
* @author 
* @version ${classInfo.version}
*/
@Service
@RequiredArgsConstructor
@Slf4j
public class ResearchProjCostSummaryServiceImpl extends ServiceImpl<ResearchProjCostSummaryMapper,ResearchProjCostSummaryModel> implements IResearchProjCostSummaryService {

    /**
    * 获取 科研项目成本汇总表列表
    *
    * @param queryForm
    * @return ApiPageResult
    * @Date 2024/09/27 09:11:36
    * @since ${classInfo.version}
    */
    @Override
    public ApiPageResult getResearchProjCostSummaryList(ResearchProjCostSummaryQueryForm queryForm) {
    IPage<ResearchProjCostSummaryModel> page = new Page<>(queryForm.getPageNo(), queryForm.getLimit());
        QueryWrapper<ResearchProjCostSummaryModel> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(queryForm.getPeriod())) {
            String period = queryForm.getPeriod();
            String fiscalYear = FiscalYearUtils.getFiscalYear(period);
            String accountingPeriod = String.valueOf(FiscalYearUtils.getAccountingPeriod(period));
            queryWrapper.eq("KJND", fiscalYear).eq("KJQJ", accountingPeriod); 
        }
            
            IPage<ResearchProjCostSummaryModel> listPage = this.baseMapper.selectPage(page, queryWrapper); 
            return new ApiPageResult(listPage.getCurrent(), listPage.getSize(), listPage.getTotal(), listPage.getRecords());
    }


    /**
    * 新增、更新 科研项目成本汇总表
    *
    * @param addForm
    * @return void
    * @Date 2024/09/27 09:11:36
    * @since ${classInfo.version}
    */
    @Override
    public void addOrUpdateResearchProjCostSummary(ResearchProjCostSummaryAddForm addForm) { 
            
    }
            

    /**
    * 通过主键ID列表删除
    *
    * @param idList
    * @param period
    * @return void
    * @Date 2024/09/27 09:11:36
    * @since ${classInfo.version}
    */
    @Override
    public void delByResearchProjCostSummaryList(List<String> idList, String period) {      
                
    }

    /**
    * 导入分析
    *
    * @param basicImportForm
    * @param importList
    * @return AnalyzeImportResultVo
    * @Date 2024/09/27 09:11:36
    * @since ${classInfo.version}
    */
    @Override
    public AnalyzeImportResultVo importAnalysis(BasicImportForm basicImportForm, List<ResearchProjCostSummaryImportExcelForm> importList) {
        AnalyzeImportResultVo analyzeImportResultVo = new AnalyzeImportResultVo();
    
        //导入总数
        Integer total = CollectionUtil.isEmpty(importList) ? 0 : importList.size();
        analyzeImportResultVo.setTotal(total);
    
        //表头
        Map<String, String> headMap = Maps.newLinkedHashMap();
                    
        headMap.put("errorMsg", "失败原因");
        analyzeImportResultVo.setHeadTab(headMap);
    
        //成功数据
        List<Map<String, Object>> successData = new ArrayList<>();
        //错误数据
        List<Map<String, Object>> errorData = new ArrayList<>();
        //所有数据
        List<List<Object>> resultList = new ArrayList<>();
    
        //会计期间
        String period = basicImportForm.getPeriod();
        String fiscalYear = FiscalYearUtils.getFiscalYear(period);
        Integer accountingPeriod = FiscalYearUtils.getAccountingPeriod(period);
        Map<String, ResearchProjCostSummaryModel> map = getConvertMapResearchProjCostSummaryMap(fiscalYear, accountingPeriod);
    
        //导入模式
        Integer importMode = basicImportForm.getImportMode();
    
        //导入解析处理
        importParseCallback(importMode, importList, map, (importExcelForm, errorMsg) -> {
            if (StrUtil.isNotBlank(errorMsg)) {
                //编码不符合规则
                Map<String, Object> errorMap = BeanUtil.beanToMap(importExcelForm);
                errorMap.put("errorMsg", errorMsg);
                resultList.add(ImportUtils.convertMapToListOfLists(errorMap));
                errorData.add(errorMap);
            } else {
                Map<String, Object> successDataMap = BeanUtil.beanToMap(importExcelForm);
                successData.add(successDataMap);
            }
            });
    
            //结果
            analyzeImportResultVo.setSuccessNum(successData.size());
            analyzeImportResultVo.setErrorNum(errorData.size());
            analyzeImportResultVo.setSuccessData(successData);
            analyzeImportResultVo.setErrorData(errorData);
    
            //构建导入分析结果文件所需参数
            List<List<String>> heads = getImportHead();
            String resultFile = ImportUtils.saveImportAnalysisFile(ImportModuleEnum.INCOME_PROJECT_RESULT, heads, resultList);
            analyzeImportResultVo.setFileUrl(resultFile);
            return analyzeImportResultVo;
    }


    /**
    * 导入 科研项目成本汇总表
    *
    * @param basicImportForm
    * @param importList
    * @return void
    * @Date 2024/09/27 09:11:36
    * @since ${classInfo.version}
    */
    @Override
    public void importResearchProjCostSummary(BasicImportForm basicImportForm, List<ResearchProjCostSummaryImportExcelForm> importList) {
        //会计期间
        String period = basicImportForm.getPeriod();
        String fiscalYear = FiscalYearUtils.getFiscalYear(period);
        Integer accountingPeriod = FiscalYearUtils.getAccountingPeriod(period);
    
        //记录日志
        String logId = insertOperatorLog(fiscalYear, accountingPeriod);
    
        AsyncImportHelper.syncImport(() -> {
       
        }, logId);
   }
                                
                                

    /**
    * 检查上一个周期的会计周期
    *
    * @param basicCopyPreviousPeriodForm
    * @return BussResultForm
    * @Date 9:21 2024/8/15
    * @since ${classInfo.version}
    */
    @Override
    public BussResultForm checkCopyLastFiscalYearData(BasicCopyPreviousPeriodForm basicCopyPreviousPeriodForm) {
        BussResultForm bussResultForm = new BussResultForm();

        //为空校验
        if (basicCopyPreviousPeriodForm == null) {
            bussResultForm.setCode(BussResultForm.UNABLE_TO_CONTINUE);
            bussResultForm.setMsg(MessageUtils.get("参数为空"));
            return bussResultForm;
        }

        //会计周期为空
        String period = basicCopyPreviousPeriodForm.getPeriod();
        if (StrUtil.isBlank(period)) {
            bussResultForm.setCode(BussResultForm.UNABLE_TO_CONTINUE);
            bussResultForm.setMsg(MessageUtils.get("请选择会计周期"));
            return bussResultForm;
        }
    
        //上一周期暂无该数据
        String fiscalYear = FiscalYearUtils.getFiscalYear(period);
        Integer accountingPeriod = FiscalYearUtils.getAccountingPeriod(period);
        //获取上一期间
        FiscalYearSimpleVo lastAccountingPeriod = fiscalYearService.getLastAccountingPeriod(fiscalYear, accountingPeriod);
        if (lastAccountingPeriod == null) {
            bussResultForm.setCode(BussResultForm.UNABLE_TO_CONTINUE);
            bussResultForm.setMsg(String.format("【%s年%d月】获取不到上一周期，无法复制，可以通过新增方式添加数据",fiscalYear,accountingPeriod));
            return bussResultForm;
        }


        //上期间数据
        LambdaQueryWrapper<ResearchProjCostSummaryModel> lastAccountingPeriodWrapper = Wrappers.lambdaQuery(ResearchProjCostSummaryModel.class);
        lastAccountingPeriodWrapper
            .eq(ResearchProjCostSummaryModel::getFiscalYear, lastAccountingPeriod.getFiscalYear())
            .eq(ResearchProjCostSummaryModel::getAccountingPeriod, lastAccountingPeriod.getAccountingPeriod());
        Integer lastAccountingPeriodCount = getBaseMapper().selectCount(lastAccountingPeriodWrapper);
        if (lastAccountingPeriodCount == 0) {
            bussResultForm.setCode(BussResultForm.UNABLE_TO_CONTINUE);
            bussResultForm.setMsg(String.format("上一周期【%s年%d月】暂无该数据，无法复制，可以通过新增方式添加数据",lastAccountingPeriod.getFiscalYear(),lastAccountingPeriod.getAccountingPeriod()));
            return bussResultForm;
        }
    
        //本期间数据
        LambdaQueryWrapper<ResearchProjCostSummaryModel> currentAccountingPeriodWrapper = Wrappers.lambdaQuery(ResearchProjCostSummaryModel.class);
        currentAccountingPeriodWrapper
                .eq(ResearchProjCostSummaryModel::getFiscalYear, fiscalYear)
                .eq(ResearchProjCostSummaryModel::getAccountingPeriod, accountingPeriod);
        Integer currentAccountingPeriodCount = getBaseMapper().selectCount(currentAccountingPeriodWrapper);
        if (currentAccountingPeriodCount == 0) {
            bussResultForm.setCode(BussResultForm.CAN_CONTINUE);
            bussResultForm.setMsg(String.format("确定要复制上一周期【%s年%d月】的数据吗？",lastAccountingPeriod.getFiscalYear(),lastAccountingPeriod.getAccountingPeriod()));
            return bussResultForm;
        }
    
        if (currentAccountingPeriodCount > 0) {
            bussResultForm.setCode(BussResultForm.CAN_CONTINUE);
            bussResultForm.setMsg(String.format("当前周期【%s年%d月】已存在数据，是否覆盖？",fiscalYear,accountingPeriod));
            return bussResultForm;
        }
                                            
                                            
        bussResultForm.setCode(BussResultForm.SUCCESS);
        return bussResultForm;
    }
                                        
                                        

    /**
    * 复制上一个会计周期
    *
    * @param basicCopyPreviousPeriodForm
    * @return void
    * @Date 9:22 2024/8/15
    * @since ${classInfo.version}
    */
    @Override
    public void copyPreviousPeriod(BasicCopyPreviousPeriodForm basicCopyPreviousPeriodForm) {
        if(basicCopyPreviousPeriodForm == null ){
            throw new BaseBusinessException("参数为空");
        }
    
        //会计周期为空
        String period = basicCopyPreviousPeriodForm.getPeriod();
        if(StrUtil.isBlank(period)){
             throw new BaseBusinessException("请选择会计周期");
        }
    
        //上一成本周期不存在
        String fiscalYear = FiscalYearUtils.getFiscalYear(period);
        Integer accountingPeriod = FiscalYearUtils.getAccountingPeriod(period);
        FiscalYearSimpleVo lastAccountingPeriod = fiscalYearService.getLastAccountingPeriod(fiscalYear, accountingPeriod);
        if(lastAccountingPeriod == null){
            throw new BaseBusinessException("上一成本周期不存在");
        }

        //上一周期暂无数据
        LambdaQueryWrapper<ResearchProjCostSummaryModel> wrapper = Wrappers.lambdaQuery(ResearchProjCostSummaryModel.class);
            wrapper
            .eq(ResearchProjCostSummaryModel::getFiscalYear,lastAccountingPeriod.getFiscalYear())
            .eq(ResearchProjCostSummaryModel::getAccountingPeriod,lastAccountingPeriod.getAccountingPeriod());
        List<ResearchProjCostSummaryModel> lastPeriodList = getBaseMapper().selectList(wrapper);
        if(CollectionUtil.isEmpty(lastPeriodList)){
                throw new BaseBusinessException("上一周期暂无数据");
        }


   }

                                 
}